package org.simplextensions.ui.view;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.simplextensions.registry.IExtensionRegistry;
import org.simplextensions.ui.SWTApplicationWindow;

public class CTabFolderViewManager extends ViewManager<CTabItemViewRegion> {

	private final Composite composite;
	private SWTApplicationWindow applicationWindow = null;

	public SWTApplicationWindow getApplicationWindow() {
		return applicationWindow;
	}

	private CTabFolder cTabFolder;

	public CTabFolderViewManager(SWTApplicationWindow applicationWindow) {
		this(applicationWindow.getExtensionRegistry(), applicationWindow.getShell());
		this.applicationWindow = applicationWindow;
	}

	public CTabFolderViewManager(IExtensionRegistry extensionRegistry, Composite composite) {
		super(extensionRegistry);
		this.composite = composite;

		this.composite.setLayout(new GridLayout());

		cTabFolder = new CTabFolder(composite, SWT.NORMAL);
		cTabFolder.setMaximizeVisible(true);
		cTabFolder.setUnselectedImageVisible(true);
		cTabFolder.setBackgroundMode(SWT.INHERIT_DEFAULT);
		cTabFolder.setSimple(false);
		cTabFolder.setTabHeight(24);
		cTabFolder.setSelectionBackground(new Color[] { composite.getDisplay().getSystemColor(SWT.COLOR_WHITE),
				composite.getDisplay().getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT)

		}, new int[] { 100 }, true);

		cTabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		cTabFolder.addSelectionListener(new SelectionAdapter() {

			public void widgetSelected(SelectionEvent arg0) {
				for (IView<CTabItemViewRegion> view : getViews()) {
					if (view.getViewRegion().getCTabItem() == cTabFolder.getSelection())
						activateView(view);
				}
			}

		});
	}

	@Override
	protected CTabItemViewRegion createViewRegion() {
		CTabItem cTabItem = new CTabItem(cTabFolder, SWT.NORMAL);
		Composite clientArea = new Composite(cTabFolder, SWT.BORDER);
		cTabItem.setControl(clientArea);

		CTabItemViewRegion viewRegion = new CTabItemViewRegion(clientArea, cTabItem);
		return viewRegion;
	}

	@Override
	protected void removeViewRegion(CTabItemViewRegion viewRegion) {
		viewRegion.getCTabItem().dispose();
	}

	@Override
	protected void activateViewRegion(CTabItemViewRegion viewRegion) {
		cTabFolder.showItem(viewRegion.getCTabItem());
	}
}
